package com.woniu.product.utils;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author LiFangyu
 * @since 2023/2/20 20:15
 */
@Slf4j
public class QrCodeUtil {

    public static void encodeQrImage(String content, int width, int height){
        // 创建二维码的生成对象
        MultiFormatWriter mfw = new MultiFormatWriter();
        // 定义二维码的类型
        BarcodeFormat type = BarcodeFormat.QR_CODE;
        // 设置二维码的参数
        Map<EncodeHintType, Object> map = new HashMap<>();
        map.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        map.put(EncodeHintType.MARGIN, 2);
        try {
            // 开始编码二维码对象
            BitMatrix bitMatrix = mfw.encode(content, type, width, height, map);
            int black = Color.BLACK.getRGB();
            int white = Color.WHITE.getRGB();
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    image.setRGB(x, y, bitMatrix.get(x, y) ? black : white);
                }
            }
            File file = new File("a.jpg");
            ImageIO.write(image, "jpg", file);
        } catch (WriterException e) {
            e.printStackTrace();
            log.error("二维码编码错误，编码的内容为{}", content);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("二维码写出错误，编码的内容为{}", content);
        }
    }

    public static String decodeQrImage(InputStream inputStream) throws Exception {
        BufferedImage image = ImageIO.read(inputStream);
        if (image == null) {
            return null;
        }
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Map<DecodeHintType, Object> hints = new HashMap<>(2);
        hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
        Result result = new MultiFormatReader().decode(bitmap, hints);
        return result.getText();
    }


}
